package anveshitha.indexers;

import static anveshitha.config.AnveshithaConstants.FILE_SEPARATOR;
import static anveshitha.config.AnveshithaConstants.LUCENE_INDEX_DIR;
import static anveshitha.config.AnveshithaConstants.indexCounter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexWriter;

import anveshitha.utils.FileUtils;


/**
 * This interface is for all source code indexers
 * 
 * @author varun
 * 
 */
public abstract class SourceCodeIndexer {

	File fIndexDir;
	String srcDir;
	boolean recursive;
	Analyzer codeAnalyzer;
	String fileExtn;

	public SourceCodeIndexer(String fileExtn, String srcDir, boolean recursive,
			Analyzer codeAnalyzer) {
		super();
		this.fileExtn = fileExtn;
		this.fIndexDir = new File(LUCENE_INDEX_DIR + fileExtn + FILE_SEPARATOR);
		this.srcDir = srcDir;
		this.recursive = recursive;
		this.codeAnalyzer = codeAnalyzer;
		indexCounter = 0;
	}

	public void index() throws FileNotFoundException {

		ArrayList<File> alFileList = FileUtils.listFiles(new File(srcDir),
				fileExtn, recursive);
		IndexWriter indexWriter = null;

		try {
			indexWriter = new IndexWriter(fIndexDir, codeAnalyzer, true);

			File tempFile = null;
			for (Iterator<File> iter = alFileList.iterator(); iter.hasNext();) {
				try {
					tempFile = iter.next();
					indexFile(indexWriter, tempFile);
					indexCounter++;
				} catch (Exception e) {
					//TODO: Apply patch for Unknown Token: 87 error
					// http://issues.apache.org/jira/browse/JAXME-77
					System.out.println("Error Creating Index on "
							+ tempFile.getAbsolutePath()
							+ "\nPlease check src and retry : "
							+ e.getMessage());
				}
			}

		} catch (IOException ioe) {
			System.err.println("IOException : " + ioe.getMessage());
		} catch (Exception e) {
			System.err.println("Exception : " + e.getMessage());
		} finally {
			try {
				indexWriter.close();
			} catch (Exception e) {
				System.err.println("Error closing indexwriter");
			}
		}

	}

	public abstract void indexFile(IndexWriter indexWriter, File file)
			throws Exception;

}
